package baseFx.database.jdbc;

import baseFx.common.utils.ExceptionUtils;
import baseFx.database.CursorReader;
import baseFx.database.SqlParam;
import baseFx.database.Utils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class JDBCCursorReader<T> implements CursorReader<T> {
    private ResultSet resultSet;
    private Class<T> clazz;
    private SqlParam param;

    public JDBCCursorReader(Class<T> clazz, SqlParam param, ResultSet rs) {
        this.clazz = clazz;
        this.resultSet = rs;
        this.param = param;
    }

    @Override
    public T next() {
        try {
            if (resultSet.next()) {
                Map row = Utils.resultSetToMap(resultSet);
                List<T> list = param.convert(clazz, Arrays.asList(row));
                return list != null && list.size() > 0 ? list.get(0) : null;
            }
            return null;
        } catch (SQLException e) {
            throw ExceptionUtils.toRuntime(e);
        }
    }

    @Override
    public void close() {
        try {
            Statement stmt = resultSet.getStatement();
            resultSet.close();
            stmt.close();
            resultSet = null;
            param = null;
            clazz = null;
        } catch (SQLException e) {
            throw ExceptionUtils.toRuntime(e);
        }
    }
}
